package com.flot.yazb.base;


import android.os.Bundle;
import android.support.annotation.AnimRes;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.flot.yazb.CUIAgent;
import com.flot.yazb.loading.ProgressManager;

import butterknife.ButterKnife;

import static android.app.Activity.RESULT_OK;

/**
 * Created by fengdongfei on 2017/8/24.
 */

public abstract class BFragment extends Fragment implements ProgressManager {
    private BActivity activity;
    private View mRootView;
    private FragmentActivity mContext;
    private BApplication app;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public final View onCreateView(LayoutInflater inflater, ViewGroup container,
                                   Bundle savedInstanceState) {

        if (mRootView == null) {
            mRootView = initRootView(inflater);
            mRootView.setClickable(true);
            ButterKnife.bind(this, mRootView);
            mContext = getActivity();
            activity = (BActivity) getActivity();
            app = (BApplication) activity.getApplication();
        }
        return mRootView;
    }
    protected abstract View initRootView(LayoutInflater inflater);
    public abstract void initView();


    public void pushFragment(int resId, BFragment fragment) {
        pushFragment(resId, fragment, 0);
    }

    public void pushFragment(int resId, BFragment fragment, int requestCode) {
        fragment.setTargetFragment(this, requestCode);
        activity.pushFragment(resId, fragment);
    }

    public void popFragment() {
        popFragment(RESULT_OK, null);
    }

    public void popFragment(int resultCode, Bundle bundle) {
        activity.onBackPressed();
    }


    public void replaceFragment(int id_content, Fragment fragment) {
        replaceFragment(id_content, 0, 0, fragment);
    }

    public void replaceFragment(@IdRes int id_content, @AnimRes int anim_in, @AnimRes int anim_out, Fragment fragment) {
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        //        transaction.setCustomAnimations(anim_in, anim_out);
        transaction.replace(id_content, fragment);
        transaction.commit();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        CUIAgent.clearCache(getActivity());
    }

    @Override
    public void showProgress() {
        CUIAgent.showProgress(getActivity());
    }

    @Override
    public void dismissProgress() {
        CUIAgent.dismissProgress(getActivity());
    }
}
